//
//  EmoticonViewController.swift
//  01表情键盘
//
//  Created by 龚欣 on 15/7/7.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit

class EmoticonViewController: UIViewController {

    private lazy var packages : [EmoticonPackage] = EmoticonPackage.packagesList!
    
    var didSelectEmoticonCallBack : (emoticon : Emoticon)->()
    
    init(didSelectEmoticon : (emoticon : Emoticon)->()){
         didSelectEmoticonCallBack = didSelectEmoticon
        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.redColor()
        
        prepareUI()
        setUpCollectionView()
        prepareToolbar()
 
    }
    
    func setUpCollectionView(){
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.pagingEnabled = true
        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.showsHorizontalScrollIndicator = false
    }
    
    func prepareToolbar(){
      
        var items = [UIBarButtonItem]()
        
        var index = 0
        for p in packages {
            let item = UIBarButtonItem(title: p.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "toolbarItemDidClick:")
            item.tag = index++
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    func toolbarItemDidClick(item : UIBarButtonItem){
        print(item.tag)
        
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }

    func prepareUI(){
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        
        var cons = [NSLayoutConstraint]()
        let viewDict = ["collectionView" : collectionView,"toolbar" : toolbar]
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolbar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict)
        view.addConstraints(cons)

    }

    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
    private lazy var toolbar : UIToolbar = UIToolbar()
   
    private class EmoticonLayout : UICollectionViewFlowLayout{
        private override func prepareLayout() {
            let s = UIScreen.mainScreen().bounds.width / 7
            itemSize = CGSize(width: s, height: s)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            let y = ((collectionView?.bounds.height)! - 3 * s) * 0.45
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
            scrollDirection = UICollectionViewScrollDirection.Horizontal
        }
    }
    
 
}

let reuseIdentifier = "reuseIdentifier"

extension EmoticonViewController : UICollectionViewDataSource,UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! EmoticonCell

        cell.emoticon = packages[indexPath.section].emoticons![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        if packages[0].emoticons!.contains(emoticon) && indexPath.section == 0 {
            didSelectEmoticonCallBack(emoticon: emoticon)
            return
        }
        
        if emoticon.png != nil || emoticon.emoji != nil{
            emoticon.times++
            packages[0].appendFavouriteEmoticon(emoticon)
        }
        
        didSelectEmoticonCallBack(emoticon: emoticon)
    }
    
}

class EmoticonCell: UICollectionViewCell {
    
    
    var emoticon : Emoticon?{
        didSet{
            if let path = emoticon?.imagePath {
                emoticonButton.setImage(UIImage(contentsOfFile: path), forState: UIControlState.Normal)
            }else{
                emoticonButton.setImage(nil, forState: UIControlState.Normal)
            }
           
            
            emoticonButton.setTitle(emoticon?.emoji ?? "" , forState: UIControlState.Normal)
            
            if  emoticon!.removeButton {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(emoticonButton)
        
        emoticonButton.userInteractionEnabled = false
        emoticonButton.frame = CGRectInset(self.bounds, 4, 4)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var emoticonButton = UIButton()
    
}
